import { BaseResponse, FileVo } from '@/types'

// 文件上传 /api/file/up   file: (binary)
export async function uploadFile(file: File) {
  try {
    const formData = new FormData()
    formData.append('file', file)

    const response = await fetch('/rpi/file/up', {
      method: 'POST',
      body: formData
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    const data = await response.json()
    return data
  } catch (error) {
    console.error('Error uploading file:', error)
  }
}

// 文件读取 /file/fs/{path} 返回文件内容
export async function loadTextFile(path: string) {
  try {
    const response = await fetch(`/file/${path}`)
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    const arrayBuffer = await response.arrayBuffer()
    const decoder = new TextDecoder('gbk')
    const data = decoder.decode(arrayBuffer)
    return data
  } catch (error) {
    console.error('Error loading file:', error)
  }
}

// 调用示例
// const fileInput = document.querySelector('input[type="file"]');
// fileInput?.addEventListener('change', (event) => {
//   const file = (event.target as HTMLInputElement).files?.[0];
//   if (file) {
//     uploadFile(file);
//   }
// });

export const removeFileExtension = (filePath: string) => {
  return filePath.replace(/\.[^/.]+$/, '')
}

export async function uploadFileToServer(file: File): Promise<FileVo> {
  try {
    const formData = new FormData()
    formData.append('file', file)

    const response = await fetch('/api/f', {
      method: 'POST',
      body: formData
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result: BaseResponse<FileVo> = await response.json()

    if (result.code !== 200) {
      throw new Error(`Upload failed: ${result.msg} (code: ${result.code})`)
    }

    return result.data
  } catch (error) {
    console.error('Error uploading file:', error)
    throw error
  }
}

//getip
export async function getIp(num: number) {
  try {
    const response = await fetch(`/api/f/ip/${num}`)
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    const data = await response.json()
    return data
  } catch (error) {
    console.error('Error getting ip:', error)
  }
}

// ip location
/**
 * <h3>
    <font color=green>您查询的IP是：182.126.223.152</font>
</h2>&nbsp;&nbsp;所在地为：河南省南阳市 联通
 * @param ip
 * @returns
 */
export async function getIpLocation(ip: string) {
  try {
    const response = await fetch(
      `/api/g/proxy?proxy=https://ip.429006.com/ip.php?action=queryip&ip_url=${ip}`
    )
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    // 提取所在地  split('所在地为：')[1].split(' ')[0]
    const data = await response.text()
    // split('所在地为：')[1].split(' ')[0]
    const location = data.split('所在地为：')[1]
    return location
  } catch (error) {
    console.error('Error getting ip location:', error)
  }
}

// ip location
export async function getIpLocationByNum(ip_num: number) {
  try {
    const ipresp = await fetch(`/api/f/ip/${ip_num}`)
    if (!ipresp.ok) {
      throw new Error(`HTTP error! status: ${ipresp.status}`)
    }
    const ipData = await ipresp.json()
    const ip = ipData.data.ip
    const response = await fetch(
      `/api/g/e/proxy?proxy=https://ip.429006.com/ip.php?action=queryip&ip_url=${ip}`
    )
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    // 处理GB2312编码的内容
    const arrayBuffer = await response.arrayBuffer()
    const decoder = new TextDecoder('gb2312')
    const decodedText = decoder.decode(arrayBuffer)
    console.log(decodedText)
    return decodedText
  } catch (error) {
    console.error('Error getting ip location:', error)
  }
}

// 获取自己的ipNum
export async function getSelfIpNum() {
  try {
    const response = await fetch('/api/f/ip/0')
    const data = await response.json()
    return data.data?.ipcode
  } catch (error) {
    console.error('Failed to fetch self IP:', error)
  }
}
